package mvc;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import utils.SpringUtil;

import mvc.mainPage.MainController;
import mvc.mainPage.MainModelCreator;

/**
 * Servlet Filter implementation class MVCFilter
 */

public class MVCFilter implements Filter {

	private static Logger log = Logger.getLogger(MVCFilter.class);
	
	private Map<String, URIMapping> mapping;
	
	private ArrayList<String> staticContent;
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
				
		log.debug("doFilter -> Start");
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        String requestURI = httpRequest.getRequestURI();
        String contextPath = httpRequest.getContextPath();
        String uri = requestURI.replace(contextPath, "");
        
        for (String content: staticContent)
        {
        	 if (uri.startsWith(content)){
        		 chain.doFilter(request, response);
        		 return;
        	 }
      			
        }
        
        //redirect from root to the main page
        if (uri.equalsIgnoreCase("/")) {
        	httpResponse.sendRedirect("main");
        	return;
        }
        
        URIMapping uriMapping = mapping.get(uri);
          
        if (uriMapping == null){
        	httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        	return;
        }
        
        log.debug(new java.util.Date ().toString () +  " incoming uri: " +uri);
        
        IModelCreator modelCreator = uriMapping.getModelCreator();
        IModel model = modelCreator.createModel(httpRequest);
        IController controller  = (IController) SpringUtil.getBeanByClass(uriMapping.getController());
        model = controller.execute(model);
        
        httpRequest.setAttribute("model", model);
        
        String view = uriMapping.getView();
        log.debug("view: " + view);
        RequestDispatcher ds= httpRequest.getRequestDispatcher(view);
        ds.forward(httpRequest, httpResponse);
           	
        // pass the request along the filter chain
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {		
		staticContent = new ArrayList<String>();
		staticContent.add("/css");
		staticContent.add("/images");
		
		mapping = new HashMap<String, URIMapping>();
		
//		URIMapping loginPageMapping = new URIMapping();
//		loginPageMapping.setUri("/login");
//		loginPageMapping.setModelCreator(new LoginModelCreator());
//		loginPageMapping.setController(LoginController);
//		loginPageMapping.setView("WEB-INF/jsp/login.jsp");
//		mapping.put(loginPageMapping.getUri(), loginPageMapping);
		
		URIMapping urimapping = URIMappingBuilder.uriMapping().
									withUri("/main").
									with(new MainModelCreator()).
									with(MainController.class).
									withView("WEB-INF/jsp/Main.jsp").build();				
		mapping.put(urimapping.getUri(), urimapping);
		
		
	}

	@Override
	public void destroy() {	}

}
